// 密钥对生成 http://web.chacuo.net/netrsakeypair   Bsoft@123456

const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n' +
    'nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=='
// const publicKey = '-----BEGIN PUBLIC KEY-----\n' +
//     'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuNTnOzzsrUq9HJChv8Lp\n' +
//     'ih19t5oZxl1Wz7oq/bsWv32dqnKAFyilJC9Dsa2CAeP7zcDg/At9SBmzre0GgJEg\n' +
//     'vGot6N3cXy4BYrrpxSY5PE8vkTnl/GhJvdSpJ4Ye+h7Qcl15ukKNs5PSlBTtBNRr\n' +
//     'vSCrADzrUeMAyaBi7WCE2reRRNoJcf93+5YgLzi+gnqJRdvRBJku9Cxnmd1a9RQI\n' +
//     'Aj3TXhNy/maY2XTJNA6+VfbqSZVVHIm82zkUlFP6WjymElbXB0D/ZVSFqPTZEeoQ\n' +
//     '3ZmCN9neukrUV7k4dc+1MIDuwrDKVCEkMfWF3GGj4Q3bzRVvBbuMaQKL1iMBoVCh\n' +
//     'VwIDAQAB\n' +
//     '-----END PUBLIC KEY-----\n';

// 加密
function encrypt(txt) {
    const encryptor = new JSEncrypt()
    encryptor.setPublicKey(publicKey) // 设置公钥
    return encryptor.encrypt(txt) // 对数据进行加密
}

// 解密
function decrypt(encryptedTxt) {
    // 校验加密字符串是否为空
    if (!encryptedTxt || typeof encryptedTxt !== 'string') {
        console.error('解密失败：加密字符串不能为空或格式错误');
        return null;
    }

    // 创建 JSEncrypt 实例并加载私钥
    const decryptor = new JSEncrypt();
    decryptor.setPrivateKey(privateKey); // 加载配对的私钥

    // 执行解密（JSEncrypt 内部已处理 Base64 解码）
    const decryptedTxt = decryptor.decrypt(encryptedTxt);

    // 校验解密结果（解密失败会返回 null）
    if (!decryptedTxt) {
        console.error('解密失败：私钥不匹配或加密字符串已被篡改');
        return null;
    }

    return decryptedTxt;
}

$(function() {
    validateKickout();
    validateRule();
    $('.imgcode').click(function() {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });
});

function login() {
    var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim($("input[name='password']").val());
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');
    if($.common.isEmpty(validateCode) && captchaEnabled) {
        $.modal.msg("请输入验证码");
        return false;
    }
    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": encrypt(password),
            "validateCode": validateCode,
            "rememberMe": rememberMe
        },
        beforeSend: function () {
            $.modal.loading($("#btnSubmit").data("loading"));
        },
        success: function(r) {
            if (r.code == web_status.SUCCESS) {
                location.href = ctx + 'index';
            } else {
                $('.imgcode').click();
                $(".code").val("");
                $.modal.msg(r.msg);
            }
            $.modal.closeLoading();
        }
    });
}

function validateRule() {
    // 移除叉号图标，直接显示错误文本
    $("#signupForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            username: {
                required: "请输入您的用户名", // 移除icon
            },
            password: {
                required: "请输入您的密码", // 移除icon
            }
        },
        submitHandler: function(form) {
            login();
        }
    })
}

function validateKickout() {
    if (getParam("kickout") == 1) {
        layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
            icon: 0,
            title: "系统提示"
        },
        function(index) {
            //关闭弹窗
            layer.close(index);
            if (top != self) {
                top.location = self.location;
            } else {
                var url = location.search;
                if (url) {
                    var oldUrl = window.location.href;
                    var newUrl = oldUrl.substring(0, oldUrl.indexOf('?'));
                    self.location = newUrl;
                }
            }
        });
    }
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}